/**
 * 定义一个require模块，并依赖app模块
 */
define(["app", "popup/popup-jpress", "util/current-tab"], function(app, jpress, currentTab) {

    /*
    平台配置, platform = {
        "valid":true,
        "reason":"",
        "nickname":"N小聪",
        "platformName":"jianshu",
        "userId":"20451298",
        "platformDisplayName":"简书"
    }
     */
    var platform;

    var init = function(item, plat){
        platform = plat;
        // 绑定菜单操作
        item.bind("click", showMenu);
        // 无效时检测是否在简书界面中
        platform.valid || detect();
    }

    // 展示配置菜单
    var showMenu = function(){
        if(!platform || !platform.valid){
            $.actions({
                title : platform.reason,
                actions: [{
                    text: "打开" + platform.platformDisplayName + "设置",
                    onClick: function(){
                        $.alert("请在新打开的窗口<br/>登陆简书账号后重新打开插件", "", goLoginPage);
                    }
                }]
            });
        } else {
            $.toptip("配置正常", 1000, "success")
        }
    }

    /**
     * 检测当前是否在简书页面，若在简书页面并且已登陆，弹出登陆信息
     */
    var detect = function(){
        if(currentTab.domain !== "www.jianshu.com"){
            return;
        }
        // 调用api查询当前页面对应的cookie
        chrome.cookies.getAll({
            "name" : "remember_user_token",
            "domain" : ".jianshu.com"
        }, function(cookies){
            // console.log("简书cookie-init：" + JSON.stringify(cookies));
            var rememberUserToken = cookies && cookies[0] ? cookies[0].value : false;
            if(!rememberUserToken){
                return;
            }
            console.log("popup.jianshu.js [jianshuDetect] - 简书cookie：" + rememberUserToken);
            $.when(
                // 查询用户
                app.sendGet(currentTab.tabId, currentTab.createUrl("/author/current_user"), cookies),
                // 查询文集
                app.sendGet(currentTab.tabId, currentTab.createUrl("/author/notebooks"), cookies)
            ).done(function(userResp, notebooksResp){
                //{"id":20451298,"nickname":"N小聪","slug":"6401987ebb8d","avatar":"https://upload.jianshu.io/users/upload_avatars/20451298/a0c9f0bb-a985-4b2e-91bb-ab6eb22f5b1f.png","preferred_note_type":"plain","can_publish_paid_note":false,"paid_note_agreement_agreed_at":null,"can_upload_audio":false,"can_update_cover_images":true,"md_auto_scroll":0,"jsd_level_for_paid_note":{"name":"白金贵族","min_score":300001},"jsd_level_for_upload_audio":{"name":"超凡大师","min_score":5000001}}
                console.log("简书用户：" + JSON.stringify(userResp))
                console.log("简书文集：" + JSON.stringify(notebooksResp))
                dologin({
                    slug : userResp.slug,
                    nickname : userResp.nickname,
                    rememberUserToken : rememberUserToken,
                    notebooks : JSON.parse(notebooksResp)
                })
            }).fail(function(e){
                $.alert(JSON.stringify(e), "系统异常");
            })
        });
    }

    /**
     * 用当前页面配置信息登陆
     * @param conf = {
            slug : "xxxxx",
            nickname : "xxxxx",
            notebooks : [{
                id : 123456,
                name : "日记本"
            }]
        }
     */
    var dologin = function(conf){
        $.confirm("是否保存名为<br/>" + conf.nickname + "（" + conf.slug + "）<br/>的简书账号", "", function() {
            // 整理文集信息并弹出选择菜单
            var actions = [];
            for (var i in conf.notebooks) {
                var notebook = conf.notebooks[i]
                actions[actions.length] = {
                    text: notebook.name,
                    onClick: function () {
                        doSaveConfig(conf.slug, notebook.id, conf.rememberUserToken)
                    }
                };
            }
            $.actions({
                title: "选择同步文集",
                actions: actions
            })
        })
    }

    // 保存配置到插件后台
    var doSaveConfig = function(slug, notebook, cookie){
        var config = {
            enable : true,
            slug : slug,
            notebook : notebook,
            cookie : "remember_user_token=" + cookie + ";"
        }
        console.log("popup-jianshu.js [doSaveConfig] - " + JSON.stringify(config));
        // 保存内容
        jpress.doSavePlatform("jianshu", config)
    }


    var goLoginPage = function(){
        // https://www.jianshu.com/sign_in
        chrome.tabs.create({'url': 'https://www.jianshu.com/sign_in'});
    }

    /**
     * 向外暴露方法
     */
    return {
        init : init
    }
})